import React, {useCallback, useEffect, useState} from 'react';
import './App.css';
import './peerPuppet'

const {ipcRenderer} = window.require('electron')

function App() {
    const [localCode, setLocalCode] = useState(null)
    const [remoteCode, setRemoteCode] = useState(null)
    const [controlText, setControlText] = useState(null)

    useEffect(async () => {
        let localCode = await ipcRenderer.invoke('login')
        localCode && setLocalCode(localCode)
    }, [])
    const onControlStatusChange = useCallback((e, name, type) => {
        if (type === 1) {
            setControlText(`正在控制${name}`)
        } else if (type === 2) {
            setControlText(`被${name}控制中`)
        }
    }, [])
    useEffect(() => {
        ipcRenderer.on('control-status-change', onControlStatusChange)
        return () => {
            ipcRenderer.removeListener('control-status-change', onControlStatusChange)
        }
    }, [onControlStatusChange])
    const onRemoteCodeChange = useCallback((e) => {
        setRemoteCode(e.target.value)
    }, [setRemoteCode])
    const startControl = useCallback(() => {
        if (remoteCode) {
            ipcRenderer.send('control', remoteCode)
        }
    }, [remoteCode])
    return (
        <div className="App">
            {
                controlText === null
                    ? <>
                        <div>本机控制码: {localCode}</div>
                        <div>
                            <input value={remoteCode} onChange={onRemoteCodeChange}/>
                            <button onClick={startControl}>请求控制</button>
                        </div>
                    </>
                    : <div>{controlText}</div>
            }
        </div>
    );
}

export default App;
